﻿using AllInOne.Classes;
using AllInOne.Models;
using AllInOne.UserControls;
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;

namespace AllInOne.MainPages
{
    /// <summary>
    /// PrintView.xaml 的交互逻辑
    /// </summary>
    public partial class PrintView : Window
    {
        WeighViewModel weighViewModel;
        DialogViewModel viewModel;
        AuthModel authModel;
        public PrintView(AuthModel authModel, int countDown)
        {
            InitializeComponent();
            this.authModel = authModel;
            viewModel = new DialogViewModel() { ShowMsg = "正在获取称重数据", CountDown = countDown };
            DataContext = viewModel;
        }

        readonly CancellationTokenSource tokenSource = new CancellationTokenSource();
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Cpb.Maximum = viewModel.CountDown;
            CancellationToken token = tokenSource.Token;

            Task countTask = new Task(() =>
            {
                while (true)
                {
                    if (!token.IsCancellationRequested)
                    {
                        viewModel.CountDown--;
                        if (viewModel.CountDown == 0)
                            QuitView(false);
                        Thread.Sleep(1000);
                    }
                    else
                        return;
                }
            }, token);
            countTask.Start();

            Task.Run(() =>
            {
                string message = string.Empty;
                //获取称重数据
                weighViewModel = DataOperate.GetWeighInfo(authModel, ref message);
                if (weighViewModel != null)
                {
                    this.Dispatcher.Invoke(new Action(() =>
                    {
                        PrintWeighControl print = new PrintWeighControl(weighViewModel);
                        PrintHelper.Print(print, "磅单");
                        viewModel.ShowMsg = "打印完成";
                    }));
                }
                else
                    viewModel.ShowMsg = message;
            });
        }

        private void QuitView(bool result)
        {
            this.Dispatcher.Invoke(new Action(() =>
            {
                tokenSource.Cancel();
                this.DialogResult = result;
                this.Close();
            }));
        }
        private void BdQuit_Click(object sender, RoutedEventArgs e)
        {
            QuitView(false);
        }
    }
}
